package club.janna.hello.schedule;

import club.janna.hello.dao.MemoryChannelDao;
import club.janna.hello.factory.GDW376D1FrameFactory;
import club.janna.hello.model.ChannelModel;
import club.janna.hello.sender.DataSender;
import club.janna.hello.util.DataConvertor;
import org.apache.commons.lang.StringUtils;

/**
 * Created by guopanbo on 18/4/18.
 */
public class QueryTask implements Runnable {
    private String id;
    private long interval;
    private byte errorCount = 0;
    private int areaCode;
    private int address;

    private int pn = 2;
    private int fn = 129;

    public QueryTask(String id, long interval, int areaCode, int address) {
        this.id = id;
        this.interval = interval;
        this.areaCode = areaCode;
        this.address = address;
    }

    @Override
    public void run() {
        sleep(5 * 1000);
        System.out.printf("开始查询任务[%s]，间隔%d秒\n", id, interval / 1000);
        while(true) {
            if (StringUtils.isBlank(id))
                throw new RuntimeException("id is null");

            ChannelModel cm = MemoryChannelDao.getInstance().doReadChannel(id);
            boolean sendFlag = false;
            if (cm != null) {
                //发送-请求数据
                sendFlag = DataSender.sendData(cm.getChannel(), DataConvertor.decArray2ByteArray(GDW376D1FrameFactory.generateQueryData(areaCode, address, pn, fn)), id);
            } else
                errorCount ++;
            if(!sendFlag)
                errorCount ++;
            if (errorCount >= 3) {
                System.out.printf("任务[%s]连续错误超过3次，中断任务\n", id);
                MemoryChannelDao.getInstance().delete(cm);
                return;
            }
            sleep(interval);
        }
    }

    /**
     * 睡眠
     * @param interval
     */
    private void sleep(long interval) {
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void setPn(int pn) {
        this.pn = pn;
    }

    public void setFn(int fn) {
        this.fn = fn;
    }
}
